package com.chainyoung.component_tmperson.ui.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.chainyoung.common.appcommon.hdwallet.OwnWalletUtils;
import com.chainyoung.common.base.BaseActivity;
import com.chainyoung.common.base.BaseApplication;
import com.chainyoung.common.base.CommonApplicationLike;
import com.chainyoung.common.bean.UserInfo;
import com.chainyoung.common.common_widget.TimeCount;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.integration.AppManager;
import com.chainyoung.common.utils.AppUtils;
import com.chainyoung.common.utils.CommonUtil;
import com.chainyoung.common.utils.SPUtil;
import com.chainyoung.common.utils.StringUtil;
import com.chainyoung.common.utils.ToastUtil;
import com.chainyoung.common.view.FixedCursorEditText;
import com.chainyoung.common.view.NoScrollListView;
import com.chainyoung.component_tmperson.R;
import com.chainyoung.component_tmperson.R2;
import com.chainyoung.component_tmperson.di.component.DaggerPersonActivityComponent;
import com.chainyoung.component_tmperson.di.module.PersonActivityModule;
import com.chainyoung.component_tmperson.ui.activity.cloudwallet.MyPurseAddrActivity;
import com.chainyoung.component_tmperson.ui.adapter.LatestAddrAdapter;
import com.chainyoung.component_tmperson.ui.mvp.contract.WithDrawContact;
import com.chainyoung.component_tmperson.ui.mvp.presenter.WithDrawPresenter;
import com.chainyoung.component_tmperson.utils.SaveInfoUtils;
import com.chainyoung.component_tmperson.zxing.Result;
import com.chainyoung.router.RouterConstants;
import com.chainyoung.router.RouterUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jnr.posix.LibC;

import static com.chainyoung.common.appcommon.hdwallet.CoinConstant.ETH;
import static com.chainyoung.component_tmperson.constant.PersonStringConstant.COIN_CN_NAME;
import static com.chainyoung.component_tmperson.constant.PersonStringConstant.COIN_NAME;
import static com.chainyoung.component_tmperson.constant.PersonStringConstant.ZC_FEE;


/**
 * 提现界面
 */

@Route(path = RouterConstants.PATH_MAKE_CASH)
public class MakeCashActivity extends BaseActivity<WithDrawPresenter> implements WithDrawContact.View {


    @BindView(R2.id.tv_addr)
    EditText etAddr;
    @BindView(R2.id.tv_num)
    EditText etNum;
    @BindView(R2.id.tv_fee_type)
    TextView tvFeeType;
    @BindView(R2.id.tv_fee_percent)
    TextView tvFeePercent;
    @BindView(R2.id.tv_send_code)
    TextView tvSendCode;
    @BindView(R2.id.et_code)
    FixedCursorEditText etCode;


    private String coinName, coinCnName, zcFee;
    private TimeCount timeCount;
    private boolean isFromOtherApp;
    private AppComponent appComponent;
    private String address = "";

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerPersonActivityComponent.builder()
                .appComponent(appComponent)
                .personActivityModule(new PersonActivityModule(this))
                .build()
                .inject(this);
        this.appComponent = appComponent;
    }


    @Override
    protected void initUI() {
        Uri uri = null;
        isFromOtherApp = getIntent().getBooleanExtra(LibConstant.FROM_OTHER_APP, false);
        if (isFromOtherApp) {
            uri = appComponent.appManager().getUri();
        } else {
            uri = getIntent().getData();
            if (uri != null) {
                appComponent.appManager().setUri(uri);
            }
        }


        if (uri != null) {
            address = uri.getQueryParameter("address");
            if (!CommonUtil.getLoginStatus()) {
                RouterUtils.getInstance()
                        .build(RouterConstants.PATH_MAIN_LOGIN)
                        .withBoolean(LibConstant.FROM_OTHER_APP, true)
                        .navigation(mContext);
                finish();
                return;
            } else {
                List<Activity> list = appComponent.appManager().getActivityList();
                if (list.size() <= 1) {
                    RouterUtils.getInstance()
                            .build(RouterConstants.PATH_VALIDATE_CODE)
                            .withBoolean(LibConstant.FROM_OTHER_APP, true)
                            .navigation(mContext);
                    finish();
                    return;
                } else {
                    isFromOtherApp = true;
                }
            }
            etAddr.setText(address);
            etAddr.setSelection(address.length());
        }

        coinName = getIntent().getStringExtra(COIN_NAME);
        coinCnName = getIntent().getStringExtra(COIN_CN_NAME);
        zcFee = getIntent().getStringExtra(ZC_FEE);
        if (isFromOtherApp) {
            coinCnName = "小比特";
            coinName = "BIT";
        }

        Drawable drawable = ContextCompat.getDrawable(mContext, R.mipmap.ic_scan);
        DrawableCompat.setTint(drawable, Color.parseColor("#061c69"));
        showAndSetBarRightIcon(drawable);

        setCurrentTitle(String.format(getString(R.string.tmperson_withdraw_title), TextUtils.isEmpty(coinCnName)?coinName.toUpperCase():coinName.toUpperCase() + "/" + coinCnName));
        tvFeeType.setText(String.format(getString(R.string.transfer_money), coinName));
        tvFeePercent.setText(TextUtils.isEmpty(zcFee) ? "0%" : zcFee + "%");
        timeCount = new TimeCount(60000, 1000, tvSendCode);
        etAddr.requestFocus();
        etAddr.setSelection(etAddr.getText().toString().length());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        isFromOtherApp = getIntent().getBooleanExtra(LibConstant.FROM_OTHER_APP, false);
        if (isFromOtherApp) {
            coinCnName = "";
            coinName = getString(R.string.tmtrade_fiat_currency);
        }
    }


    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_make_cash;
    }


    //---------------------------------------------------点击事件------------------------------------------------------------------------

    @OnClick(R2.id.tv_confirm)
    void onConfirm() {
        if (StringUtil.viewGetTextIsEmpty(etAddr)) {
            ToastUtil.showToast("请输入转出地址");
            return;
        }
        if (!StringUtil.isWalletAddrValidate(etAddr.getText().toString().trim())) {
            ToastUtil.showToast("请输入正确的不包含空格中文的钱包地址");
            return;
        }

        if (StringUtil.viewGetTextIsEmpty(etNum)) {
            ToastUtil.showToast("请输入转出数量");
            return;
        }
        if (etCode.getText().toString().length() != 6) {
            ToastUtil.showToast("请输入6位数字验证码");
            return;
        }

        if (StringUtil.viewGetTextIsEmpty(etCode)) {
            ToastUtil.showToast(etCode.getmHint().toString());
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("")
                .setMessage(R.string.tmperson_sure_to_withdraw)
                .setPositiveButton(mContext.getString(R.string.yes), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //保存最近地址
                        TreeMap<String, Object> map = new TreeMap<>();
                        map.put("token", SPUtil.getString(LibConstant.TOKEN));
                        map.put("coin", coinName);
                        map.put("verify_code", StringUtil.viewGetText(etCode));
                        map.put("number", StringUtil.viewGetText(etNum));
                        map.put("address", StringUtil.viewGetText(etAddr));
                        mPresenter.withDraw(map);
                        dialog.dismiss();
                    }
                })
                .setNegativeButton(mContext.getString(R.string.no), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create();
        builder.show();


    }

    @OnClick(R2.id.tv_send_code)
    void sendCode() {
        if (CommonUtil.isFastDoubleClick()) {
            return;
        }
        UserInfo userInfo = CommonUtil.getUserInfo();
        String accountNo = TextUtils.isEmpty(userInfo.getMobile()) ? userInfo.getEmail() : userInfo.getMobile();
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("account", accountNo);
        map.put("type", "withdraw");
        map.put("token", SPUtil.getString(LibConstant.TOKEN));
        mPresenter.sendCode(map);
    }


    @Override
    public void onRightImgClicked(View v) {
        Intent intent = new Intent(mContext, ScanQrCodeActivity.class);
        mContext.startActivityForResult(intent, REQUEST_ADDR);
    }

    private static final int REQUEST_ADDR = 0x001;

    @OnClick(R2.id.iv_purse)
    void selectAddr() {
        Intent intent = new Intent(mContext, MyPurseAddrActivity.class);
        intent.putExtra("selectCloudAddr", true);
        mContext.startActivityForResult(intent, REQUEST_ADDR);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        String addr = data.getStringExtra("data");

        List<String> wordsList = new ArrayList<>();
        try {
            wordsList.addAll(Arrays.asList(addr.split(" ")));
        } catch (Exception ignore) {

        }
        if (wordsList.size() == 12) {
            addr = OwnWalletUtils.getWalletAddr(addr, ETH);
        } else if (addr.contains(":")) {
            addr = addr.substring(addr.lastIndexOf(":") + 1);
        }

        etAddr.setText(addr);
        etAddr.setSelection(addr.length());
    }

    //------------------------------------------网络请求-------------------------------------------------------

    @Override
    public void onWithDrawSuccess(String data) {
        ToastUtil.showToast(getString(R.string.tmperson_withdraw_success));
        finish();
    }

    @Override
    public void onSendCodeSuccess(String object) {
        showMsg(getString(R.string.validate_code_sent));
        timeCount.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //判断app是否登录  没有登录去跳转到登录界面
        if (!CommonUtil.getLoginStatus()) {
            RouterUtils.getInstance()
                    .build(RouterConstants.PATH_MAIN_LOGIN)
                    .withBoolean(LibConstant.FROM_OTHER_APP, true)
                    .navigation(mContext);
            finish();

        }
    }

    @Override
    protected void onDestroy() {
        if (timeCount != null) {
            timeCount.cancel();
        }
        super.onDestroy();
    }


}
